import { isFunction } from '@material/helpers';
import { FC, cloneElement, isValidElement, memo } from 'react';
import { MessageInfo } from '../chat/message/type';

import $style from './index.scss';
import { isArray, isString } from '@tarojs/shared';
export interface ChatItemProps extends MessageInfo {
    isLast?: boolean;
}

const renderChatItem = function (props: ChatItemProps) {
    const { component, ...rest } = props;
    if (isFunction(component)) {
        return component({ ...rest });
    }
    if (isValidElement(component)) {
        return cloneElement(component, { ...rest });
    }
    if (!component) {
        return isString(props.Content) || isArray(props.Content) ? props.Content : '';
    }
    return component;
};

export const ChatItem: FC<ChatItemProps> = function (props: ChatItemProps) {
    if (!props) {
        return null;
    }
    if (props.component) {
        return <div className={$style.item}>{renderChatItem(props)}</div>;
    }
    if (props.FromType === 'user' && !props.Event) {
        return (
            <div className={[$style.item, $style.right]}>
                <div className={$style.send}>
                    {isString(props.Content) || isArray(props.Content) ? props.Content : ''}
                </div>
            </div>
        );
    }
    if (props.FromType !== 'user') {
        return (
            <div className={[$style.item, $style.left]}>
                {isString(props.Content) || isArray(props.Content) ? props.Content : ''}
            </div>
        );
    }
};

export const ChatItemComponent = memo(ChatItem);
